<?php

/**
 * @filename source_class.php 2013-11-11 02:10:56x
 * @author Huming Xu <huming17@126.com>
 * @version 1.0.0
 * @copyright DZF (c) 2013, Huming Xu
 */
if (!defined('IN_SITE')) {
    exit('Access Denied');
}

class ctrl_upload_main extends upload_main {

    public $info_array = array();
    public $page_array = array();
    public $tree_array = array();

    static function &instance() {
        static $object;
        if (empty($object)) {
            $object = new self();
        }
        return $object;
    }

    /*
     * 	xheditor编辑器获取远程图片
     */

    public function do_get_remote_img() {
        global $_G;
        //DEBUG 调试输出
        if (!empty($_G['user_id'])) {
            //DEBUG xheditor编辑器获取远程图片
            $attachDir = 'data/upload'; //上传文件保存路径，结尾不要带/
            $upExt = "jpg,jpeg,gif,png";
            $arrUrls = explode('|', $_POST['urls']);
            $urlCount = count($arrUrls);
            for ($i = 0; $i < $urlCount; $i++) {
                $localUrl = $this->saveRemoteImg($arrUrls[$i]);
                if ($localUrl)
                    $arrUrls[$i] = $localUrl;
            }
            echo implode('|', $arrUrls);
        }
    }

    /*
     * 文件上传
     * 注1：本程序特别针对HTML5上传,加入了特殊处理
     * @author xuhm
     * @todo 安全校验
     */

    public function do_file() {
        global $_G;
        @set_time_limit(0);
        //ini_set("display_errors","On");
        //error_reporting(E_ALL);
        //@file_put_contents(SITE_ROOT.'./data/debug/file_request_log_'.date('Ymd').'.txt','RETURN : '.date('Y-m-d H:i:s').' '.  json_encode($_REQUEST).PHP_EOL,FILE_APPEND);
        //@file_put_contents(SITE_ROOT.'./data/debug/file_input_log_'.date('Ymd').'.txt','RETURN : '.date('Y-m-d H:i:s').' '.json_encode($_FILES).PHP_EOL,FILE_APPEND);
        header('Content-Type: text/html; charset=UTF-8');
        $inputName = 'filedata'; //表单文件域name       
        $attachDir = !empty($_G['setting']['server_upload'][1]['dirpath']) ? SITE_ROOT . 'data/' . $_G['setting']['server_upload'][1]['dirpath'] : PATH_UPLOAD . 'data/upload'; //上传文件保存路径，结尾不要带/        
        $dirType = !empty($_G['setting']['server_upload'][1]['dirtype']) ? $_G['setting']['server_upload'][1]['dirtype'] : 1; //1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存
        $maxAttachSize = !empty($_G['setting']['server_upload'][1]['maxsize']) ? $_G['setting']['server_upload'][1]['maxsize'] : 50000000; //最大上传大小，默认是50M
        $upExt = !empty($_G['setting']['server_upload'][1]['upext']) ? $_G['setting']['server_upload'][1]['upext'] : 'apk,rar,zip,pdf,doc,docx,ppt,pptx,xls,xlsx,jpg,jpeg,png,jpg,mp3,mp4,mov,amr'; //上传扩展名
        $msgType = 2; //返回上传参数的格式：1，只返回url，2，返回参数数组
        //ini_set('date.timezone','Asia/Shanghai');//时区
        /*
         * thumb 1 表示需要 缩略图; 2 表示不需要缩略图 
         */     
        $thumb = isset($_REQUEST['thumb']) && !empty($_REQUEST['thumb']) ? $_REQUEST['thumb'] : '';
        $thumb_width = isset($_REQUEST['thumb_width']) && !empty($_REQUEST['thumb_width']) ? $_REQUEST['thumb_width'] : '200';
        $thumb_height = isset($_REQUEST['thumb_height']) && !empty($_REQUEST['thumb_height']) ? $_REQUEST['thumb_height'] : '200';
        $files_store = isset($_REQUEST['files_store']) && !empty($_REQUEST['files_store']) ? $_REQUEST['files_store']:'';//1表示 需要数据表pre_file_source存储文件名 返回表fs_id 空或其他返回存储路径
        $err = "";
        $msg = array();
        $tempPath = $attachDir . '/' . date("YmdHis") . mt_rand(10000, 99999) . '_' . random(4) . '.tmp';
        $file_name = '';
        $return_array = array("code" => 'e_0001', "msg" => lang('error', 'e_0001'), "data" => $msg);
        if(!empty($_G['user_id']) || 1 == 1){
            if(!is_dir($attachDir)){
                @mkdir($attachDir, 0777);
                @fclose(fopen($attachDir . '/index.htm', 'w'));
            }
            
            if(isset($_SERVER['HTTP_CONTENT_DISPOSITION']) && preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i', $_SERVER['HTTP_CONTENT_DISPOSITION'], $info)) {//HTML5上传
                file_put_contents($tempPath, file_get_contents("php://input"));
                $file_name = urldecode($info[2]);
            }
            else{//标准表单式上传
                $upfile = @$_FILES[$inputName];
                if(!isset($upfile)){
                    $return_array = ["code" => 'e_2001', "msg" => lang('error', 'e_2001'), "data" => $msg];
                }
                elseif(!empty($upfile['error'])){
                    switch($upfile['error']){
                        case '1':
                            $return_array = ["code" => 'e_2002', "msg" => lang('error', 'e_2002'), "data" => $msg];
                            break;
                        case '2':
                            $return_array = ["code" => 'e_2003', "msg" => lang('error', 'e_2003'), "data" => $msg];
                            break;
                        case '3':
                            $return_array = ["code" => 'e_2004', "msg" => lang('error', 'e_2004'), "data" => $msg];
                            break;
                        case '4':
                            $return_array = ["code" => 'e_2005', "msg" => lang('error', 'e_2005'), "data" => $msg];
                            break;
                        case '6':
                            $return_array = ["code" => 'e_2006', "msg" => lang('error', 'e_2006'), "data" => $msg];
                            break;
                        case '7':
                            $return_array = ["code" => 'e_2007', "msg" => lang('error', 'e_2007'), "data" => $msg];
                            break;
                        case '8':
                            $return_array = ["code" => 'e_2008', "msg" => lang('error', 'e_2008'), "data" => $msg];
                            break;
                        case '999':
                        default:
                            $return_array = ["code" => 'e_2009', "msg" => lang('error', 'e_2009'), "data" => $msg];
                    }
                }
                elseif(empty($upfile['tmp_name']) || $upfile['tmp_name'] == 'none') {
                    $return_array = ["code" => 'e_2005', "msg" => lang('error', 'e_2005'), "data" => $msg];
                }
                else{
                    $this->upload_file($upfile['tmp_name'], $tempPath);
                    if (!file_exists($tempPath)) {
                        $return_array = ["code" => 'e_2010', "msg" => lang('error', 'e_2010'), "data" => $msg];
                    }
                    $file_name = $upfile['name'];
                }
            }

            if (empty($err)) {
                $fileInfo = pathinfo($file_name);
                $extension = $fileInfo['extension'];
                if (preg_match('/^(' . str_replace(',', '|', $upExt) . ')$/i', $extension)) {
                    $bytes = filesize($tempPath);
                    if ($bytes > $maxAttachSize) {
                        $return_array = ["code" => 'e_2011', "msg" => str_replace('###XXX###', $this->formatBytes($maxAttachSize), lang('error', 'e_2011')), "data" => $msg];
                    } else {
                        switch ($dirType) {
                            case 1: $attachSubDir = '/' . 'day_' . date('Ymd');
                                break;
                            case 2: $attachSubDir = '/' . 'month_' . date('Ym');
                                break;
                            case 3: $attachSubDir = '/' . 'ext_' . $extension;
                                break;
                        }
                        
                        $tAttachDir = $attachDir;//本地服务器存放的上传路径
                        
                        $attachDir = $attachDir.$attachSubDir;
                        
                        PHP_VERSION < '4.2.0' && mt_srand((double) microtime() * 1000000);
                        $newFilename = date("YmdHis") . mt_rand(1000, 9999) . '_' . random(4) . '.' . $extension;
                        $tTargetPath = $tAttachDir . '/' . $newFilename;
                        $targetPath = $attachDir . '/' . $newFilename;
                        //DEBUG 阿里云OSS处理 TODO 待优化示例 http://help.aliyun.com/manual?spm=0.0.0.0.vVdtHC&helpId=181
                        if ($_G['setting']['aliyun_oss']) {
                            $this->upload_file($tempPath, $tTargetPath, $attachSubDir.'/');
                        } else {
                            rename($tempPath, $tTargetPath);
                            @chmod($tTargetPath, 0755);
                        }
                        
                        if(!empty($thumb) && !empty($thumb_width) && !empty($thumb_height) && $files_store != 1){
                            if(strpos($thumb_width,",")){
                                $thumb_width_array = explode(',',$thumb_width);
                                $thumb_height_array = explode(',',$thumb_height);
                            }
                            else{
                                $thumb_width_array[0] = $thumb_width;
                                $thumb_height_array[0] = $thumb_height;
                            }
                            
                            $thumb_num = count($thumb_width_array)-1;
                            for($i=0; $i<=$thumb_num; $i++){
                                list($img_width, $img_height) = getimagesize($tTargetPath);
                                $thumbfile = '../'.$attachSubDir.'/'.$newFilename.'_thumb_'.$thumb_width_array[$i].'.jpg';
                                if(($img_width > $thumb_width_array[$i]) || ($img_height > $thumb_height_array[$i])){
                                    require_once libfile('class/image');
                                    $img = new image;
                                    $thumb_result = $img->Thumb($tTargetPath, $thumbfile, $thumb_width_array[$i], $thumb_height_array[$i]);
                                    if(!$thumb_result) {
                                        $return_array = ["errcode"=>'e_2013',"errmsg"=>lang('error','e_2013'),"data"=>$msg];
                                    }
                                }
                                else{
                                    $this->upload_file($tTargetPath, $tTargetPath.'_thumb_'.$thumb_width_array[$i].'.jpg', $attachSubDir.'/');
                                }
                                
                                sleep(1);
                            }
                        }
                                                          
                        $target_path = str_replace(PATH_UPLOAD, '', $targetPath);  
                        $target_path_json = $this->jsonString($target_path);
                        if($files_store != 1){
                            if($msgType == 1){
                                $msg = "'$target_path_json'";
                            }
                            else{
                                $msg = ['url'   =>  'http://fstore.jxzhjy.com/'.$target_path, 'file_name'   =>  $file_name];
                            }
                        }
                        else{
                            //DEBUG 需要数据表pre_file_source存储文件名 返回是文件 fs_id
                            $grade_id = isset($_REQUEST['grade_id']) ? $_REQUEST['grade_id']:'';
                            $subject_id = isset($_REQUEST['subject_id']) ? $_REQUEST['subject_id']:'';
                            $file_path_array = explode('/',$target_path);
                            $count_key = count($file_path_array)-1;
                            $file_name_array = pathinfo($file_name);
                            $data = [
                                'user_id'           =>  $_G['user_id'],
                                'fs_name'           =>  str_replace('.'.$file_name_array['extension'],'',$file_name),
                                'fs_extension'      =>  strtolower($file_name_array['extension']),
                                'fs_store_path'     =>  trim($attachSubDir,'/'),//TODO 优化各种路径 随配置而变化 现在默认存储路劲是 4
                                'fs_real_name'      =>  str_replace('.'.$file_name_array['extension'],'',$file_path_array[$count_key]),
                                'fs_grade_id'       =>  $grade_id,
                                'fs_subject_id'     =>  $subject_id,
                                'fs_size'           =>  filesize(PATH_UPLOAD.'./'.$target_path),
                                'create_dateline'   => TIMESTAMP
                            ];
                            $insert_id = DB::insert('file_source',$data,1);
                            if($insert_id){
                                $msg = ['url'   =>  'http://fstore.jxzhjy.com/'.$target_path, 'file_name'   =>  $file_name, 'fs_id'  =>    $insert_id];
                            }
                        }
                    }
                }
                else{
                    $return_array = ["code" => 'e_2014', "msg" => lang('error', 'e_2014') . $upExt, "data" => $msg];
                }
                
                @unlink($tempPath);
            }
            
            if(file_exists($tTargetPath)){
                $return_array = ["code" => '0', "msg" => lang('error', 'e_2000'), "data" => $msg];
            }
            else{
                $return_array = ["code" => 'e_2015', "msg" => lang('error', 'e_2015'), "data" => $msg];
            }
        }
        else{
            //DEBUG 无权限上传
            $return_array = ["code" => 'e_2016', "msg" => lang('error', 'e_2016'), "data" => $msg];
        }
        
        if(empty($_G['gp_api'])){
            $_G['gp_api'] = 'json';
        }
        
        //2017-6-5 15:28:49 此处加入上传远端服务器判断
        //如果返回结果中存在url，并且不为空，且该文件存在
        if(isset($return_array['data']['url']) && $return_array['data']['url'] && file_exists($tTargetPath)){

            $data = ['filedata'  =>  new CURLFile($tTargetPath), 'dir' => $attachSubDir.'/'];
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            curl_setopt($ch, CURLOPT_URL, 'http://101.37.15.34/upload.php');
            curl_setopt($ch, CURLOPT_POST, true );
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

             $res = curl_exec($ch);
             curl_close($ch);
             
             //此处删除掉本地的文件
             @unlink($tTargetPath);
             
             if($res == 'success'){//成功
                 $return_array = ["code" => '0', "msg" => lang('error', 'e_2000'), "data" => $msg];
             }
             else{//远程文件上传失败
                 $return_array = ["code" => 'e_2015', "msg" => lang('error', 'e_2015'), "data" => $msg];
             }
        }
        
        echo format_data($return_array, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    //apk文件上传
    public function do_apk_file(){
    	global $_G;
        @set_time_limit(0);
        
    	$version = isset($_REQUEST['apkVersion']) && !empty($_REQUEST['apkVersion']) ? $_REQUEST['apkVersion'] : '12';//版本号
    	$file = isset($_REQUEST['file']) && !empty($_REQUEST['file']) ? $_REQUEST['file'] : '';
    	//上传登录验证
    	if(!$_G['user_id']){
            $noauth = [
                'code'  =>  '10000',
                'msg'   =>  lang('core','noauth'),
                'data'  =>  []
            ];
            
            echo json_encode($noauth, JSON_FORCE_OBJECT);
            return false; 
    	}
        
    	if(!$_FILES["file"]["name"]){
            $return['code'] = '1';
            $return['data'] = [];
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
    	}
        
    	$filename = date("YmdHis") . mt_rand(1000, 9999) .'_' .random(4). '_'.$_FILES["file"]["name"];    	
    	
        $tTarget = PATH_UPLOAD.'data/upload/';
        
        $tTargetPath = $tTarget.$filename;
        
    	if(!is_dir($tTarget)){   	
            $res = mkdir(iconv("UTF-8", "GBK", $tTarget), 0777, true);
    	}
        
    	$insert_data = [
            'version'           =>  $version,
            'a_name'            =>  $filename,
            'create_dateline'   =>  TIMESTAMP,
            'is_new'            =>  '1'
    	];
        
    	$res = $this->add_apk('apk', $insert_data);
//        $res = 1;
    	if($res){
            $this->upload_file($_FILES["file"]["tmp_name"], $tTargetPath);
            if(is_file($tTargetPath)){
                
                $data = ['filedata'  =>  new CURLFile($tTargetPath), 'dir' => '/apk/'];
                $ch = curl_init();

                curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
                curl_setopt($ch, CURLOPT_URL, 'http://101.37.15.34/upload.php');
                curl_setopt($ch, CURLOPT_POST, true );
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                curl_setopt($ch, CURLOPT_HEADER, false);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                 $res = curl_exec($ch);
                 curl_close($ch);

                 //此处删除掉本地的文件
                 @unlink($tTargetPath);

                 if($res == 'success'){//成功
                    $return['code'] = '0';
                    $return['data']['url'] = 'http://fstore.jxzhjy.com/data/upload/apk/'.$filename;
                 }
                 else{//远程文件上传失败
                    $return['code'] = '1';
                    $return['data']= [];
                 }
            }
            else{
                $return['code'] = '1';
                $return['data']= [];
            }
    	}
        else{
            $return['code'] = '2';
            $return['data']= [];
    	}
    	
    	echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
    	return false;
    	
    }
    
    //apk是否最新
    public function do_is_new(){
    	global $_G;
    	$version = isset($_REQUEST['apkVersion']) && !empty($_REQUEST['apkVersion']) ? $_REQUEST['apkVersion'] : '1';//版本号
    	    	
    	$insert_data = ['version' => $version];
    	$res = $this->is_new('apk', 'version', $version);
    	if($res){
            $return['code'] = '0';
            if($res['is_new'] == 1){
                $return['data']['isNew'] = true;
                $return['data']['apkUrl'] = '';
            }
            else{
                $res_new = $this->get_new('apk', 'is_new', '1');
                if($res_new){
                    $return['code'] = '0';
                    $return['data']['isNew'] = false;
                    $return['data']['apkUrl'] = 'http://fstore.jxzhjy.com/data/upload/apk/'.$res_new['a_name'];
                }
                else{
                    $return['code'] = '1';
                    $return['data'] = [];
                }
            }
    	}
        else{
            $res_new = $this->get_new('apk', 'is_new', '1');
            if($res_new){
                $return['code'] = '0';
                $return['data']['isNew'] = false;
                $return['data']['apkUrl'] = 'http://fstore.jxzhjy.com/data/upload/apk/'.$res_new['a_name'];
            }
            else{
                $return['code'] = '1';
                $return['data'] = [];
            }
    	}	
    
    	echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
    	return false;
    }
    
    //删除apk
    public function do_apk_delete() {
    	global $_G;
    	if(!$_G['user_id']){
    		$noauth = [
    				'code'=>'10000',
    				'msg'=>lang('core','noauth'),
    				'data'=>[]
    		];
    		echo json_encode($noauth,JSON_FORCE_OBJECT);return false;
    	
    	}
		$a_id = isset($_REQUEST['a_id']) ? $_REQUEST['a_id'] : '';
		if($a_id){
			$effect_row = $this->delete("apk", array("a_id" => $a_id));
			if($effect_row){
				$return['code'] = '0';
				$return['data']=array();
				echo format_data($return,$_G['gp_api'],$_G['gp_mod'],$_G['gp_action'],$_G['gp_do']);
			}else{
				$return['code'] = '1';
				$return['data']=array();
				echo format_data($return,$_G['gp_api'],$_G['gp_mod'],$_G['gp_action'],$_G['gp_do']);
			}
		}
    	
    }
    
    /*
     *  apk列表信息
     *
     * @param $table_name string.
     * @param $page_condition array.
     *
     * @return array
     */
    public function do_apk_list($table_name,$page_condition){
    	global $_G;
    	$page = max(1, intval($_GET['page']));
    	$perpage = $limit = isset($_REQUEST['limit']) && !empty($_REQUEST['limit']) ? $_REQUEST['limit'] : '10';;
    	$start=(($page-1) * $perpage);
    	$wheresql = "";
    	$wheresql .= " AND isdelete = 0";
    	//apk文件id
    	$a_id = isset($_REQUEST['a_id']) && !empty($_REQUEST['a_id']) ? $_REQUEST['a_id'] : '';;
    	if($a_id){
    		$wheresql .= " AND a_id = ".$a_id;
    	}
    	//版本号
    	$version = isset($_REQUEST['apkVersion']) && !empty($_REQUEST['apkVersion']) ? $_REQUEST['apkVersion'] : '';;
    	if($version){
    		$wheresql .= " AND version = ".$version;
    	}    	
    	$orderby = " ORDER BY is_new DESC ,create_dateline DESC";
    	//DEBUG 初始化请求请求获取一页列表数据的参数
    	$page_condition=array(
    			'page' => $page,//int 请求页面 页码
    			'limit' => $limit,//int 每页请求个数
    			'perpage' => $perpage,//int 每页显示个数
    			'wheresql' => $wheresql,//string //条件SQL语句
    			'orderby' => $orderby,//string 排序规则
    	);
    	$page_result = $this->apk_list('apk',$page_condition);
    		
    	//$content_cate_title_array = $this->get_field_value_by_id('content_cate','info_cateid',$info_cateid_array,'title');
    	//DEBUG 获取各类信息分类名称 结束
    	//DEBUG 返回输出
    	$api=isset($_REQUEST['api']) ? $_REQUEST['api']:'json';
    	if($page_result){
    		$return['code'] = '0';
    		if($page_info){
    			$return['data']=$page_result;
    		}else{
    			$return['data']=$page_result['page_data'];
    		}
    		echo format_data($return,$_G['gp_api'],$_G['gp_mod'],$_G['gp_action'],$_G['gp_do']);
    	}else{
    		$return['code'] = '1';
    		$return['data']=array();
    		echo format_data($return,$_G['gp_api'],$_G['gp_mod'],$_G['gp_action'],$_G['gp_do']);
    	}
    		
    }
    
    public function upload_file($src_file, $target_file, $dir = ''){
        @copy($src_file,$target_file);
        if(!file_exists($target_file) && function_exists('move_uploaded_file'))
        {
            @move_uploaded_file($src_file,$target_file);
        }
        if(!file_exists($target_file))
        {
            if (@is_readable($src_file) && (@$fp_s = fopen($src_file, 'rb')) && (@$fp_t = fopen($target_file, 'wb'))) {
                while (!feof($fp_s)) {
                    $s = @fread($fp_s, 1024 * 512);
                    @fwrite($fp_t, $s);
                }
                fclose($fp_s); fclose($fp_t);
            }
        }
        
        //此处判断一下是否已经存好了该文件
        if(file_exists($target_file) && $dir){

            $data = ['filedata'  =>  new CURLFile($target_file), 'dir' => $dir];
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            curl_setopt($ch, CURLOPT_URL, 'http://101.37.15.34/upload.php');
            curl_setopt($ch, CURLOPT_POST, true );
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            curl_exec($ch);
            curl_close($ch);
             
            //此处删除掉本地的文件
            @unlink($target_file);
        }
        
    }
    /*
     * ajax 返回信息
     */

    public function return_json($error, $message, $output = 1) {
        $return_array = array(
            "error" => $error,
            "message" => $message
        );
        if ($output) {
            echo json_ext($return_array);
            die;
        } else {
            return json_ext($return_array);
        }
    }

}

?>